@{
    ViewData["Title"] = "入库明细";
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>@ViewData["Title"]</title>
    <link rel="stylesheet" href="~/layui/css/layui.css">
</head>
<body>
    <div class="layui-container" style="padding: 20px;">
        <!-- 入库单基本信息 -->
        <fieldset class="layui-elem-field">
            <legend>入库单信息</legend>
            <div class="layui-field-box">
                <div class="layui-row">
                    <div class="layui-col-md3">
                        <strong>入库单编号：</strong><span id="lnboundCode"></span>
                    </div>
                    <div class="layui-col-md3">
                        <strong>入库单名称：</strong><span id="lnboundName"></span>
                    </div>
                    <div class="layui-col-md3">
                        <strong>供应商：</strong><span id="vendor"></span>
                    </div>
                    <div class="layui-col-md3">
                        <strong>状态：</strong><span id="status"></span>
                    </div>
                </div>
                <div class="layui-row" style="margin-top: 10px;">
                    <div class="layui-col-md3">
                        <strong>入库日期：</strong><span id="lnboundDate"></span>
                    </div>
                    <div class="layui-col-md3">
                        <strong>入库仓库：</strong><span id="lnboundWarehous"></span>
                    </div>
                    <div class="layui-col-md3">
                        <strong>采购订单号：</strong><span id="procurementNumber"></span>
                    </div>
                    <div class="layui-col-md3">
                        <strong>总金额：</strong><span id="totalAmount"></span>
                    </div>
                </div>
            </div>
        </fieldset>

        <!-- 入库明细 -->
        <fieldset class="layui-elem-field layui-field-title">
            <legend>入库明细</legend>
        </fieldset>

        <!-- 操作按钮（仅草稿状态显示） -->
        <div class="layui-form-item" id="btnSection" style="display: none;">
            <button type="button" class="layui-btn layui-btn-sm" id="btnAddDetail">
                <i class="layui-icon layui-icon-add-1"></i> 添加明细
            </button>
        </div>

        <table class="layui-hide" id="detailTable" lay-filter="detailTable"></table>

        <div style="text-align: center; margin-top: 20px;">
            <button type="button" class="layui-btn layui-btn-primary" onclick="parent.layer.closeAll()">关闭</button>
        </div>
    </div>

    <script src="~/layui/layui.js"></script>
    <script>
        layui.use(['table', 'form', 'layer'], function () {
            var $ = layui.jquery;
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;

            var procurementId = '@ViewBag.Id';
            var documentStatus = 0; // 当前单据状态

            // 加载入库单基本信息
            loadProcurementInfo();

            // 初始化明细表格
            var detailTableIns = table.render({
                elem: '#detailTable',
                url: '/Procurement/GetDetails',
                where: { procurementId: procurementId },
                cols: [[
                    { field: 'materialCode', title: '物料编码', width: 120, templet: function(d) { return d.materialCode || ''; } },
                    { field: 'materialName', title: '物料名称', width: 150, templet: function(d) { return d.materialName || ''; } },
                    { field: 'specifications', title: '规格型号', width: 120, templet: function(d) { return d.specifications || ''; } },
                    { field: 'inputNum', title: '入库数量', width: 100, templet: function(d) { return d.inputNum || 0; } },
                    { field: 'unit', title: '单位', width: 80, templet: function(d) { return d.unit || ''; } },
                    { field: 'money', title: '金额', width: 100, templet: function(d) { return d.money ? d.money.toFixed(2) : '0.00'; } },
                    { field: 'batch', title: '批次', width: 100, templet: function(d) { return d.batch || ''; } },
                    { field: 'inDate', title: '入库日期', width: 120, templet: function(d) { return formatDate(d.inDate); } },
                    { field: 'desc', title: '描述', width: 150, templet: function(d) { return d.desc || ''; } }
                ]],
                page: false,
                response: { 
                    statusCode: 0
                },
                parseData: function(res) {
                    console.log('明细数据:', res);
                    return {
                        "code": res.code,
                        "msg": res.msg,
                        "count": res.data ? res.data.length : 0,
                        "data": res.data || []
                    };
                },
                done: function(res) {
                    console.log('表格渲染完成，数据条数:', res.data ? res.data.length : 0);
                }
            });

            // 添加明细按钮
            $('#btnAddDetail').on('click', function() {
                addDetail();
            });

            // 加载入库单基本信息
            function loadProcurementInfo() {
                $.get('/Procurement/GetProcurement', { id: procurementId }, function(result) {
                    console.log('获取采购入库信息:', result);
                    if (result.success) {
                        var data = result.data;
                        documentStatus = data.documentStatus;
                        
                        $('#lnboundCode').text(data.lnboundCode || '');
                        $('#lnboundName').text(data.lnboundName || '');
                        $('#vendor').text(data.vendor || '');
                        $('#status').html(getStatusBadge(data.documentStatus));
                        $('#lnboundDate').text(formatDate(data.lnboundDate));
                        $('#lnboundWarehous').text(data.lnboundWarehous || '');
                        $('#procurementNumber').text(data.procurementNumber || '-');
                        $('#totalAmount').text((data.totalAmount || 0).toFixed(2));

                        // 只有草稿状态才显示添加明细按钮
                        if (data.documentStatus === 0) {
                            $('#btnSection').show();
                        } else {
                            $('#btnSection').hide();
                        }
                    } else {
                        console.error('获取采购入库信息失败:', result.message);
                        layer.msg('获取采购入库信息失败: ' + (result.message || '未知错误'));
                    }
                }).fail(function(xhr, status, error) {
                    console.error('请求失败:', xhr, status, error);
                    layer.msg('请求失败，请检查网络连接');
                });
            }

            // 添加明细
            function addDetail() {
                layer.open({
                    type: 2,
                    title: '添加入库明细',
                    shadeClose: true,
                    shade: 0.8,
                    area: ['700px', '600px'],
                    content: '/Procurement/AddDetail?procurementId=' + procurementId,
                    end: function() {
                        // 关闭弹窗后刷新表格
                        detailTableIns.reload();
                        loadProcurementInfo();
                    }
                });
            }

            // 获取状态标识
            function getStatusBadge(status) {
                if (status === 0) {
                    return '<span class="layui-badge layui-bg-gray">草稿</span>';
                } else if (status === 1) {
                    return '<span class="layui-badge layui-bg-blue">已提交</span>';
                } else if (status === 2) {
                    return '<span class="layui-badge layui-bg-green">已完成</span>';
                } else {
                    return '<span class="layui-badge">未知</span>';
                }
            }

            // 格式化日期
            function formatDate(dateStr) {
                if (!dateStr) return '';
                try {
                    var date = new Date(dateStr);
                    if (isNaN(date.getTime())) return '';
                    return date.getFullYear() + '-' +
                        ('0' + (date.getMonth() + 1)).slice(-2) + '-' +
                        ('0' + date.getDate()).slice(-2);
                } catch (e) {
                    console.error('日期格式化错误:', dateStr, e);
                    return '';
                }
            }
        });
    </script>
</body>
</html> 